package com.jdk.learn.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 创建线程的几种方式
 *  1.继承Thread
 *  2.实现Runnable
 *  3.匿名内部类
 *  4.实现callable
 *  5.线程池
 *
 */
public class ThreadDemao {
    /**
     * 设置为守护线程后，该线程随着主线程执行结束而结束
     * @param args
     * @throws InterruptedException
     */
    public static void main2(String[] args) throws InterruptedException {
        Thread demo = new Thread(new _02(), "示例线程");
        demo.setDaemon(true);//守护线程
        demo.start();
        for (int i = 0; i < 5; i++) {
            Thread.sleep(1000);
            System.out.println("idMain:"+Thread.currentThread().getId()+"----"+i);
        }
        System.out.println("------结束");
    }
    /**
     * 设置为非守护线程后，该线程不随着主线程执行结束而结束
     * 打印----结束后会继续执行
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {
        Thread demo = new Thread(new _02(), "示例线程非守护");
//        demo.setDaemon(true);//守护线程
        demo.start();
        for (int i = 0; i < 5; i++) {
            Thread.sleep(1000);
            System.out.println("idMain:"+Thread.currentThread().getId()+"----"+i);
        }
        System.out.println("------结束");
    }

}
class _01 extends Thread{
    @Override
    public void run() {
        System.out.println("继承Thread方式的线程创建");
    }

    public static void main(String[] args) {
        new _01().start();
    }
}

class _02 implements Runnable{

    @Override
    public void run() {
        System.out.println("实现runnable方式");
        for (int i = 0; i < 20; i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("id:"+Thread.currentThread().getId()+"----"+i);
        }
    }

    public static void main(String[] args) {
        new Thread(new _02()).start();
    }
}
class _03 {

    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("匿名内部类方式");
            }
        }).start();
    }
}
class _04 implements Callable{


    @Override
    public Object call() throws Exception {
        System.out.println("实现callable接口");
        return null;
    }
}
class _05{

    public static void main(String[] args) {
        ExecutorService service= Executors.newFixedThreadPool(10);
        service.submit(()->{
            System.out.println("线程池方式");
        });
        service.shutdownNow();
        service=null;
    }
}
